package com.feng.service.impl;

import com.feng.domain.ResponseResult;
import com.feng.domain.entity.LoginUser;
import com.feng.domain.entity.User;
import com.feng.domain.vo.BlogUserLoginVo;
import com.feng.domain.vo.UserInfoVo;
import com.feng.service.BlogLoginService;
import com.feng.service.LoginService;
import com.feng.util.BeanCopyUtils;
import com.feng.util.JwtUtil;
import com.feng.util.RedisCache;
import com.feng.util.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class LoginServiceImpl implements LoginService {
    //需要要securtiyConfig进行装入bean容器
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisCache redisCache;
    @Override
    public ResponseResult login(User user) {
        //该类为Authenticate的实现类，传入用户的账号密码
        UsernamePasswordAuthenticationToken authenticationToken=new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
        //进行认证，会调用userDetailService进行用户认证，默认认证方式是内存进行查询
        // 所以我们需要重写一个方法，使其实现userDetailService类，让其从数据库进行查询认证，此项目调用UserDetailsServiceImpl
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        //判断是否认证通过
        if(Objects.isNull(authenticate)){
            throw new RuntimeException("用户名或密码错误");
        }
        //获取userid生成token
        LoginUser loginUser= (LoginUser) authenticate.getPrincipal();
        Long id = loginUser.getUser().getId();
        String userid = id.toString();
        String jwt = JwtUtil.createJWT(userid);
        //把用户信息存入redis
        redisCache.setCacheObject("login:"+userid,loginUser);
        //把token与userInfo封装并返回
        BlogUserLoginVo blogUserLoginVo=new BlogUserLoginVo();
        Map<String,String> map=new HashMap<>();
        map.put("token",jwt);


        return ResponseResult.okResult(map);
    }

    @Override
    public ResponseResult logout() {
        //获取当前登录用户的id
        Long userId = SecurityUtils.getUserId();
        String s = userId.toString();
        //删除redis中对应的值
        redisCache.deleteObject("login:"+s);

        return ResponseResult.okResult();

    }


}
